/**
 * Copyright (c) 2010, QinJian
 * All rights reserved.
 */
package com.q.course.service.user;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.annotations.common.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.q.course.bean.common.BeanUtils;
import com.q.course.dao.user.UserDao;
import com.q.course.entity.user.User;
import com.q.course.modules.security.utils.Digests;
import com.q.course.modules.utils.Encodes;

/**
 * @author 覃健,Email:j411@qq.com
 *
 */
@Component
@Transactional
public class UserService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;
	
	@Autowired
	private UserDao userDao;

	public Object[] saveUser( User user ){
		if(StringHelper.isNotEmpty( user.getPassword() )){
			entryptPassword(user);
		}
		if( user.getId()!=null ){
			User sUser = userDao.findOne(user.getId());
			BeanUtils.copyProperties(user, sUser);
			userDao.save(sUser);
		}
		else{
			userDao.save(user);
		}
		
		return new Object[]{true, user.getId()};
	}

	@Transactional( readOnly=true )
	public User findUserByLoginName( String loginName ){
		return userDao.findByExistStateAndLoginName(true, loginName);
	}
	
	@Transactional( readOnly=true )
	public User getUserById( Long id ){
		return userDao.findByExistStateAndId(true, id);
	}
	
	@Transactional( readOnly=true )
	public List<Object[]> getTeachers( Date date ){
		
		Calendar calendar  =  Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(calendar.DATE, 1);
		Date firstd = calendar.getTime();
		
		calendar.roll(calendar.DATE, -1);
		Date lastd = calendar.getTime();
		lastd = new Date( lastd.getTime()+ 86399999 );
		
		return userDao.findByExistState( firstd, lastd );
	}
	
	@Transactional( readOnly=true )
	public List<User> getTeacherList(){
		return userDao.findByExistState(true);
	}
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}
}
